package sensimulator;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import sennetworkserver.LaneStore;

/**
 * Reads an input file and plays back the events defined there.
 */
public class InputFileReader {
	
	/**
	 * A single line in the input file
	 *
	 */
	private class InputFileLine {
		
		private int timeStamp;
		
		private int laneId;
		
		public InputFileLine(int timeStamp, int laneId) {
			this.timeStamp = timeStamp;
			this.laneId = laneId;
		}
		
	}
	
	/**
	 * A timer task which executes a single input file line
	 *
	 */
	private class InputFileTask extends TimerTask {
		
		private InputFileLine task;
		
		public InputFileTask(InputFileLine task) {
			this.task = task;
		}

		@Override
		public void run() {
			// Notify observers of the sensor
			LaneStore.getLane(task.laneId).getSensor100m().notifyObservers();
		}
		
	}

	private Timer timer;
	
	private List<InputFileLine> lines;
	
	public InputFileReader() {
		lines = new ArrayList<InputFileLine>();
		timer = new Timer("InputFileReader", true);
	}
	
	public void generate(int amount, int timeSpan) {
		for (int i = 0; i < amount; i++) {
			int laneId = (int) Math.round(1 + (Math.random() * 27));
			int timestamp = (int) (((float) timeSpan) / ((float) amount)) * i;
			lines.add(new InputFileLine(timestamp, laneId));
		}
	}
	
	public void write(String fileName) throws IOException {
		BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
		
		System.out.println("Writing input file " + fileName);
		
		for (InputFileLine line : lines)
			writer.write(line.timeStamp + " " + line.laneId + "\n");
		
		writer.flush();
		writer.close();
	}
	
	public void read(String fileName) throws FileNotFoundException {
		BufferedReader reader = new BufferedReader(new FileReader(fileName));

		System.out.println("Reading input file " + fileName);
		
		String line;
		
		try {
			lines.clear();
			
			while ((line = reader.readLine()) != null) {
				String[] chunks = line.split("[^0-9]");	// Split on any non decimal character

				if (chunks.length > 2)
					System.out.println("Invalid input line: " + line);
				else
					lines.add(new InputFileLine(Integer.valueOf(chunks[0]),
							 					Integer.valueOf(chunks[1])));
			}
			
			System.out.println("Processed " + lines.size() + " lines");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void schedule() {
		for (InputFileLine line : lines)
			timer.schedule(new InputFileTask(line), line.timeStamp);
	}
	
	
	
}
